package com.syqc.videos

import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.syqc.comlib.UserConstant
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.AppContext
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.HistoryVideo
import com.syqc.entity.VideoState
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import com.syqc.utils.TimeUtil
import com.syqc.utils.VideoHostUtil
import java.net.URLEncoder
import java.util.UUID

class TmnPlayerVM : AutoDisposeViewModel() {
    private val userIdEncode =
        URLEncoder.encode(UserConstant.current_userId.replace(".", "_"), "utf-8")
    private val user = "$userIdEncode*${UserConstant.current_pwd_md5}"

    //视频集群地址
    private var videoHost: String = ""
    private lateinit var entity: HistoryVideo.Result


    //播放类型
    var videoType = 0

    //车辆ID
    var carId: String = ""
        set(value) {
            field = value
            if (value.isNotEmpty()) {
                val host = VideoHostUtil.getVideoHost(field)
                videoHost = VideoHostUtil.getHost(host)
            }
        }

    private var uuid = ""

    //倍数
    var multiple = 0

    //滑动时间
    var seekToTime = ""

    //最大时长
    var maxTime = 0L

    //视频状态
    val videoToastLive = MutableLiveData<String>()

    //视频模式
    val videoStateLive = MutableLiveData<Int>()

    //初始化
    fun handleEntity(videoEntity: HistoryVideo.Result) {
        entity = videoEntity
        maxTime = TimeUtil.instance.getDiffLockTime(entity.startTime, entity.endTime)
    }

    fun setSeekTime(progress: Long) {
        seekToTime = TimeUtil.instance.getAddLockTime(entity.startTime, progress)
    }

    fun getName(): String =
        entity.channelName ?: (AppContext.getDescById(R.string.desc_video_pass) + entity.channel)

    fun stopPlay() {
        videoType = 0
        operateVideo()
    }

    fun pauseVideo() {
        videoType = 1
        operateVideo()
    }

    fun resumeVideo() {
        videoType = 5
        operateVideo()
    }

    fun fastVideo() {
        videoType = 2
        operateVideo()
    }

    fun frameVideo() {
        videoType = 4
        operateVideo()
    }

    fun backVideo() {
        videoType = 3
        operateVideo()
    }


    fun multipleVideo(multiple: Int) {
        this.multiple = multiple
        operateVideo()
    }

/////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 通过时间获取视频链接
     *
     * @param time
     * @return
     */
    fun getUrlTime(time: String? = null): String {
        entity.run {
            multiple = 0
            uuid = UUID.randomUUID().toString()

            return "$videoHost/httpflv.hplay.$uuid.$user.$carId.$channel.$avType.$streamType.$storeType.$videoType.$multiple.${
                time ?: startTime
            }.$endTime"
        }
    }

    /**
     * 获取操作后的拼接链接
     *
     * @return
     */
    private fun getOperateUrl(): String {
        if (uuid.isEmpty()) return ""
        val baseParam = "$videoHost/httpflv.hctr"

        when (videoType) {
            //关闭
            0 -> return "$baseParam.close.$uuid"
            //暂停
            1 -> return "$baseParam.pause.$uuid"
            //快进
            2 -> return "$baseParam.fast.$uuid.$multiple"
            //快退
            3 -> return "$baseParam.back.$uuid.$multiple"
            //关键帧播放
            4 -> return "$baseParam.iframe.$uuid"
            //恢复播放
            5 -> return "$baseParam.resume.$uuid"
            //拖动播放
            else -> return "$baseParam.seek.$uuid.$seekToTime"// 时间差后计算时间格式yymmddhhmmss
        }
    }

    /**
     * 获取播放失败状态URL
     *
     * @return
     */
    private fun getErrorStateUrl(): String {
        return "$videoHost/httpflv.state.$uuid"
    }
/////////////////////////////////////////////////////////////////////////////////////////////////

    private fun operateVideo() {
        val url = getOperateUrl()
        ServiceHelper.getRepository().getVideoState(url)
            .autoDispose(this)
            .subscribe({
                val data = GsonUtil.formObject<VideoState?>(it)
                if ("0" == data?.state) {
                    videoStateLive.postValue(videoType)
                    return@subscribe
                }
                videoToastLive.postValue(it)
            }, {
                if (videoType != 0)
                    videoToastLive.postValue("66")
            })
    }

    /**
     * 获取失败原因
     *
     */
    fun getErrorState() {
        ServiceHelper.getRepository().getVideoState(getErrorStateUrl())
            .autoDispose(this).subscribe({
                if (it.isNullOrEmpty()) {
                    videoToastLive.postValue("66")
                    return@subscribe
                }
                val value = if (!it.endsWith("}")) {
                    "$it}"
                } else {
                    it
                }
                val result = GsonUtil.formObject<VideoState?>(value)

                if (result == null) {
                    videoToastLive.postValue("66")
                } else {
                    videoToastLive.postValue(result.state ?: "66")
                }
            }, {
                if (videoType != 0)
                    videoToastLive.postValue("66")
            })
    }


    fun reset() {
        videoType = 0
        multiple = 0
    }

}